<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller
{
	protected $_templates;
	
	function __construct() 
	{
        parent::__construct();
		$this->permit_library->check_permit();
		$this->session->set_userdata(array('Url'=>uri_string()));   
		$this->pre_message = "";
		$this->load->model('user_model','user');
		$this->load->helper('search');
	}
	
	function index()
	{
		/*Begin search*/
        $type = $this->input->post('type');
       
        $current_router = $this->router->fetch_class();
        if($this->session->userdata('current_router')&&$this->session->userdata('current_router')!=$current_router){
            $this->session->set_userdata('key_search','');
        }
        $this->session->set_userdata('current_router',$current_router);

        $data['search_bar']=searchBar(array(),array('email'=>'Email','fullname'=>'FullName','nickname'=>'NickName'),'user/index');
        if($type=='ajax')
        {
            $arr_search['key_search'] = $this->input->post('key_search');
            $arr_search['field_search'] = $this->input->post('field_search');
            $this->session->set_userdata('key_search',$arr_search['key_search']);
            $this->session->set_userdata('field_search',$arr_search['field_search']);
        }
        else{
            $arr_search['key_search']=$this->session->userdata('key_search');
            $arr_search['field_search']=$this->session->userdata('field_search');
        }
        /*End  search*/
		
		$data['title'] = lang('index');
		$data['add'] = 'user/add';
		$data['export'] = 'user/export';
		
		
		$config['base_url'] = base_url().'user/index/'.(int)$this->uri->segment(3);  
		$data['num'] = $this->user->get_num_user($arr_search);
		$config['total_rows']   =  $data['num'];
		$config['per_page']  =   '20';
		$config['uri_segment'] = 4;   
		$config['num_links'] = 40;   
		$this->pagination->initialize($config);   
		$data['list'] =   $this->user->get_all_user($config['per_page'],(int)$this->uri->segment('4'),$arr_search);
		$data['pagination']    = $this->pagination->create_links();            
		
		$this->_templates['page'] = 'user/index';
		if($type=="ajax")
            echo $this->load->view($this->_templates['page'],$data,true);
		else
			$this->site->load($this->_templates['page'],$data);
	}
	
    function settings_upload_avatar()
	{
        $member_id = $this->input->post('member_id');
        $lb_image  = $this->input->post('lb_image');
        if($member_id>0&&$member_id!=''){
            $dir = '../uploads/avatar/';
            $size=$_FILES['uploadfile']['size'];
            if($size>204857600)
            {
                echo "file_biger";
                unlink($_FILES['uploadfile']['tmp_name']);
                exit;
            }
            $filename = stripslashes($_FILES['uploadfile']['name']);
            $extension = strtolower(file_extension($filename));

            if($extension =='jpeg')
            {
                $extension = 'jpg';
            }
            $name = date("dmYHis");
            $file_ext = $name.'.'.$extension;
            $filename = $dir.$file_ext;
            if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $filename))
            {
                if($file_ext!=''){
                    fn_resize_image('../uploads/avatar/'.$file_ext,'../uploads/avatar/135/'.$file_ext,135,135);
                    @chmod('../uploads/avatar/'.$file_ext,0777);
                    @unlink('../uploads/avatar/'.$file_ext);
                }
                /*$data_img = array(
                    'ImageLink' => $dir,
                    'ImageName' => $file_ext,
                    'ImageType' => $extension,
                );
                //Resize Images and add to dadtabase
                $data['fileid'] = $this->profile->add_image($data_img);*/

                $this->user->save_user($member_id,array('lb_image'=>$file_ext));
                if($lb_image!=''&&$lb_image!='avatar_male.jpg'&&$lb_image!="avatar_female.jpg"){
                        @chmod('../uploads/avatar/135/'.$lb_image,0777);
                        @unlink('../uploads/avatar/135/'.$lb_image);
                }
                $data['img'] =  $file_ext ;
                echo json_encode($data) ;
            }else{
                echo 'error';
            }
        }else{
            echo 'error';
        }
	}
  
	function add()
	{
		$data['title'] = lang('add');
		$data['login_code'] = $this->user->get_list_login_code(0);
		
		$this->form_validation->set_rules('fullname',lang('full_name'),'trim|required');
		$this->form_validation->set_rules('username',lang('nick_name'),'trim|required');
		$this->form_validation->set_rules('lb_email', lang('email'), 'trim|required|valid_email');
		$this->form_validation->set_rules('lb_password',lang('password'),'trim|required');
		$this->form_validation->set_rules('nb_gender',lang('gender'),'trim|required');
		$this->form_validation->set_rules('lb_day',lang('day'),'required');
		$this->form_validation->set_rules('lb_month',lang('month'),'required');
		$this->form_validation->set_rules('lb_year',lang('year'),'required');
		
		if($this->form_validation->run()== FALSE){
			$this->pre_message = validation_errors();
		}else{
			$rs = $this->user->get_user_check($_POST['lb_email']);
			if(count($rs) >0){
				$this->pre_message =  lang('email_exist');
			}else{
			
			  $data = $this->build_data($_POST,1);
			  if($this->user->save_user(0,$data)){
					 if($this->input->post('lb_image')!=''){
						 if(file_exists('../uploads/user/'.$this->input->post('lb_image'))){
							// unlink('../uploads/user/'.$this->input->post('lb_image'));
						 }
						//fn_resize_image('../uploads/images/'.$this->input->post('lb_image'),'../uploads/user/'.$this->input->post('lb_image'),160,120); 
					  }                      
					  $this->session->set_flashdata('message',lang('save_success'));
					  redirect('user/index');
				  }
			  }
	  }
	
	  $data['message'] = $this->pre_message;
	  $data['timezones']=$this->config->item('fm_time_zone','config_globalvar');
	  $this->_templates['page'] = 'user/user_add_view';
	  $this->site->load($this->_templates['page'],$data);
	}

	function edit($member_id)
	{
		$data['rs'] = $this->user->get_user_item($member_id);
		$data['title'] = lang('update').' '.$data['rs']->fullname;
		
		if(isset($_POST['bt_submit']))
		{
			$this->form_validation->set_rules('fullname',lang('full_name'),'trim|required');
			$this->form_validation->set_rules('username',lang('nick_name'),'trim|required');
			$this->form_validation->set_rules('lb_email', lang('email'), 'trim|required|valid_email');
			
			if($this->form_validation->run()== FALSE){
				  $this->pre_message = validation_errors();
			}else{
				$data = $this->build_data();
				if($this->user->save_user($member_id,$data)){
					/*if($this->input->post('lb_image')!=''){
						if(file_exists('../uploads/user/'.$this->input->post('lb_image'))){
						// unlink('../uploads/user/'.$this->input->post('lb_image'));
						}
					//fn_resize_image('../uploads/images/'.$this->input->post('lb_image'),'../uploads/user/'.$this->input->post('lb_image'),160,120); 
					}    */                  
					$this->session->set_flashdata('message',lang('save_success'));
					redirect('user/index');
				}
			}			
		}

		
	
		$data['message'] = $this->pre_message;
		
		$this->_templates['page'] = 'user/edit';
		$this->site->load($this->_templates['page'],$data);
	}
	
	function view()
	{
		$member_id = (int)$this->uri->segment(3);
	  
		$data['rs'] = $this->user->get_user_item($member_id);
		$data['login_code'] = $this->user->get_list_login_code(0);
		$data['title'] = lang('update').' '.$data['rs']->fullname;
		
		$data['message'] = $this->pre_message;
		$data['timezones']=$this->config->item('fm_time_zone','config_globalvar');
		
		$arr_birth_day = explode('/',$data['rs']->lb_birthday);
		$data['rs']->lb_day='';
		$data['rs']->lb_month='';
		$data['rs']->lb_year='';
		if(is_array($arr_birth_day))
		{
			$data['rs']->lb_day=isset($arr_birth_day[0])?$arr_birth_day[0]:'';
			$data['rs']->lb_month=isset($arr_birth_day[1])?$arr_birth_day[1]:'';
			$data['rs']->lb_year=isset($arr_birth_day[2])?$arr_birth_day[2]:'';
		}
		
		$this->_templates['page'] = 'user/user_view';
		$this->site->load($this->_templates['page'],$data);
	}
	
	function del()
	{
		$id = $this->uri->segment(3);
		$page = $this->uri->segment(4);
		if($this->user->save_user($id, array('bl_active'=>-1)))
			$this->session->set_flashdata('message',lang('delete_success'));
		else $this->session->set_flashdata('message',lang('delete_unsuccess'));
		redirect('user/index/'.$page);
	}
  
	function dels()
	{
		if(!empty($_POST['ar_id']))
		{
			$page = (int)$this->input->post('page');
			$ar_id = $this->input->post('ar_id');
			
			if(!empty($_POST['btn_submit']))
			{
				for($i = 0; $i < sizeof($ar_id); $i ++)
				{
					if ($ar_id[$i])
					{
						if($this->user->save_user($ar_id[$i],array('bl_active'=>-1)))
							$this->session->set_flashdata('message',lang('delete_success'));
						else $this->session->set_flashdata('message',lang('delete_unsuccess'));
					}
				}
			}
		}
		redirect('user/index/'.$page);
	}  
	  
	function build_data($flag=1)
	{
		$dataUpdate["fullname"]= $this->input->post("fullname");
		$dataUpdate["username"]=$this->input->post("username");
        $dataUpdate["lb_email"]=$this->input->post("lb_email");
		$dataUpdate["nb_phone"]=$this->input->post("nb_phone");
		$dataUpdate["address"]=$this->input->post("address");
		$dataUpdate["lb_website"]=$this->input->post("lb_website");
        $dataUpdate["lb_yahoo"]=$this->input->post("lb_yahoo");
        $dataUpdate["lb_skype"]=$this->input->post("lb_skype");
        $dataUpdate["lb_msn"]=$this->input->post("lb_msn");
		$dataUpdate["bl_active"]= (int) $this->input->post("bl_active");
		
		if($flag!=1){
			$dataUpdate["dt_create"] = date("Y-m-d H:i:s");
		}
		return $dataUpdate;
	}

	function export()
	{
		$data['title'] = 'Xuất thông tin thành viên';
		$this->form_validation->set_rules('tungay','Ngày bắt đầu','required');
		$this->form_validation->set_rules('denngay','Ngày kết thúc','required');
		if($this->form_validation->run() == false)
		{
			$this->pre_message = validation_errors();
		}
		else
		{
			$list = $this->user->export_user();
			ini_set('memory_limit', '100M');
			memory_get_peak_usage(true);
			require_once APPEXCEL.'excel/PHPExcel.php';
			// Create new PHPExcel object
			
			$this->phpexcel = new PHPExcel(); 
			// Set properties
			$this->phpexcel->getProperties()->setCreator("Viet Tien Phong Advertising Company Ltd.")
												  ->setLastModifiedBy("Viet Tien Phong Advertising Company Ltd")
												  ->setTitle("Thong ke thanh vien")
												  ->setSubject("Thong ke thanh vien")
												  ->setDescription("File thong ke thanh vien. Author: VietBuzzAD.")
												  ->setKeywords("office 2007 openxml php")
												  ->setCategory("Thong ke thanh vien");
			
			$this->phpexcel->getDefaultStyle()->getFont()->setName('Arial');
			$this->phpexcel->getDefaultStyle()->getFont()->setSize(10);            
			// SET HEADER FILE EXCEL
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('A1', 'Danh sách thành viên từ '.date("d/m/Y",strtotime($this->input->post('tungay'))).' đến ngày '.date("d/m/Y",strtotime($this->input->post('denngay'))));          
			//STT
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('A3', 'STT');
			$this->phpexcel->getActiveSheet()->getColumnDimension('A')->setWidth(10); 
			//Ma don hang
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('B3', 'Tên Thành Viên'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('B')->setWidth(35); 
			// Tình trang
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('C3', 'Email');
			$this->phpexcel->getActiveSheet()->getColumnDimension('C')->setWidth(35);
			// Số lượng SP
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('D3', 'Ngày Sinh');
			$this->phpexcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
			// Tong tien
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('E3', 'Giới tính'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
			// Tong tien
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('F3', 'Điện Thoại'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
			// NV xử lý đơn hàng
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('G3', 'Địa Chỉ'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('G')->setWidth(35);                     
			// THong tin thanh toan
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('H3', 'Yahoo'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('H')->setWidth(7);   
			// THong tin nhận hàng
			$this->phpexcel->setActiveSheetIndex(0)->setCellValue('I3', 'Skype'); 
			$this->phpexcel->getActiveSheet()->getColumnDimension('I')->setWidth(7); 
			$i=4;
			$k=1;
			foreach($list as $rs):
			
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('A'.$i, $rs->member_id);		//$k
				 //Ma don hang
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('B'.$i, $rs->fullname); 
				 // Tình trang
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('C'.$i, $rs->lb_email);
				 // Số lượng SP
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('D'.$i, $rs->lb_birthday);
				 // Tong tien
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('E'.$i, $rs->nb_gender); 
				 // Tong tien
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('F'.$i, $rs->nb_phone);   
				 // NVKD
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('G'.$i, $rs->address);      
				 // Thong tin thanh toan        
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('H'.$i, $rs->lb_yahoo);           
				 // Thong tin nhan hang
				 $this->phpexcel->setActiveSheetIndex(0)->setCellValue('I'.$i, $rs->lb_skype);     
			$i++;
			$k++;
			endforeach;
			//set Font
			$this->phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
			$this->phpexcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
		
			// Witdh
			$this->phpexcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
			$this->phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setName('Tahoma');
			$this->phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(14); 
			$this->phpexcel->getActiveSheet()->getStyle('A2')->getFont()->setName('Tahoma');
			$this->phpexcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14);                
			// Rename sheet
			 $this->phpexcel->getActiveSheet()->setTitle('Thongke');
		
			 
			// Set active sheet index to the first sheet, so Excel opens this as the first sheet
			 $this->phpexcel->setActiveSheetIndex(0);
		
			$date = date('h_i_s_d_m_Y',time());
			// Redirect output to a client's web browser (Excel5)
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename="member_'.$date.'.xls"');
			header('Cache-Control: max-age=0');
		
			$objWriter = PHPExcel_IOFactory::createWriter( $this->phpexcel, 'Excel5');
			$objWriter->save('php://output');
			exit;                       
			
		}
		$data['message'] = $this->pre_message;
		$this->_templates['page'] = 'user/export';
		$this->site->load($this->_templates['page'],$data);
	}

	function search()
	{
		
	}
}
?>
